"""
OpenCV插件

提供OpenCV视频分析功能的插件实现。
"""

import asyncio
from typing import Any, Dict, List

from src.core.plugin import ProcessorPlugin
from src.core.di import Inject
from src.modules.analyzers import OpenCVAnalyzer
from src.core.ast import Ast, AstContext

class OpenCVPlugin(ProcessorPlugin):
    """
    OpenCV插件
    
    集成OpenCV分析器到插件系统中。
    """
    
    def __init__(self):
        super().__init__()
        self.analyzer: OpenCVAnalyzer = None
    
    @property
    def name(self) -> str:
        return "OpenCVPlugin"
    
    @property
    def version(self) -> str:
        return "1.0.0"
    
    @property
    def description(self) -> str:
        return "基于OpenCV的视频分析插件"
    
    @property
    def author(self) -> str:
        return "MixVideo Team"
    
    @property
    def dependencies(self) -> List[str]:
        return []
    
    def get_supported_operations(self) -> List[str]:
        return ["analyze_video", "detect_scenes", "extract_features", "analyze_frames"]
    
    async def on_init(self, ctx: 'Any') -> None:
        """初始化插件"""
        
        # 从依赖注入容器获取OpenCV分析器
        from src.core.di import injector
        
        try:
            self.analyzer = injector.get(OpenCVAnalyzer)
        except Exception:
            # 如果没有注册，创建新实例
            config = ctx.get_global_config("opencv", {})
            logger = ctx.get_logger(self.name)
            self.analyzer = OpenCVAnalyzer(config={"opencv": config}, logger=logger)
        
    
    def on_compiler(self, ast: Any, ctx: 'AstContext') -> Any:
        """编译时处理"""
        # 暂时简化实现
        return ast

    def on_execute(self, ast: Any, ctx: 'AstContext') -> Any:
        """执行时处理"""
        # 暂时简化实现
        return ctx
    
    async def process(self, input_data: Any, **kwargs) -> Any:
        """处理数据"""
        if not self.analyzer:
            raise RuntimeError("OpenCV分析器未初始化")
        
        operation = kwargs.get('operation', 'analyze_video')
        return await self.analyzer.process(input_data, operation, **kwargs)
    
    async def classify(self, input_data: Any, **kwargs) -> Any:
        """分类数据（不适用于OpenCV插件）"""
        raise NotImplementedError("OpenCV插件不支持分类功能")
    
    async def output(self, data: Any, **kwargs) -> Any:
        """输出数据（不适用于OpenCV插件）"""
        raise NotImplementedError("OpenCV插件不支持输出功能")
    
    def _validate_opencv_config(self, ast: 'Ast') -> None:
        """验证OpenCV配置"""
        if not hasattr(ast, 'input_path') or not ast.input_path:
            raise ValueError("OpenCV节点缺少输入路径")
        
        if hasattr(ast, 'scene_threshold') and (ast.scene_threshold < 0 or ast.scene_threshold > 1):
            raise ValueError("场景检测阈值必须在0-1之间")
        
        if hasattr(ast, 'sample_rate') and (ast.sample_rate <= 0 or ast.sample_rate > 1):
            raise ValueError("采样率必须在0-1之间")
    
    def _execute_opencv_analysis(self, ast: 'Ast', ctx: Any) -> Dict[str, Any]:
        """执行OpenCV分析"""
        if not self.analyzer:
            raise RuntimeError("OpenCV分析器未初始化")
        
        # 获取参数
        input_path = getattr(ast, 'input_path', ctx.get_data('input_path'))
        operation = getattr(ast, 'operation', 'analyze_video')
        scene_threshold = getattr(ast, 'scene_threshold', 0.3)
        sample_rate = getattr(ast, 'sample_rate', 1.0)
        max_frames = getattr(ast, 'max_frames', 1000)
        
        if not input_path:
            raise ValueError("未指定输入视频路径")
        
        # 异步执行分析
        async def analysis_task():
            return await self.analyzer.process(
                input_path,
                operation=operation,
                scene_threshold=scene_threshold,
                sample_rate=sample_rate,
                max_frames=max_frames
            )
        
        # 在事件循环中运行
        try:
            loop = asyncio.get_event_loop()
            if loop.is_running():
                # 如果已经在事件循环中，创建任务
                task = asyncio.create_task(analysis_task())
                # 这里需要等待任务完成，但不能在同一个事件循环中await
                # 实际实现中应该使用适当的异步处理方式
                result = {}  # 临时返回空结果
            else:
                result = loop.run_until_complete(analysis_task())
        except RuntimeError:
            # 没有事件循环，创建新的
            result = asyncio.run(analysis_task())
        
        # 更新上下文数据
        if operation == 'analyze_video':
            ctx.set_data('video_analysis', result)
            ctx.set_data('scene_count', result.get('scene_count', 0))
            ctx.set_data('frame_count', result.get('frame_count', 0))
        elif operation == 'detect_scenes':
            ctx.set_data('scenes', result)
            ctx.set_data('scene_count', len(result) if isinstance(result, list) else 0)
        elif operation == 'extract_features':
            ctx.set_data('video_features', result)
        elif operation == 'analyze_frames':
            ctx.set_data('frame_analysis', result)
            ctx.set_data('analyzed_frame_count', len(result) if isinstance(result, list) else 0)
        
        return {
            'input_path': input_path,
            'operation': operation,
            'result': result
        }
    
    async def on_destroy(self) -> None:
        """销毁插件"""
        self.analyzer = None


# 插件元数据
PLUGIN_METADATA = {
    "name": "OpenCVPlugin",
    "version": "1.0.0",
    "description": "基于OpenCV的视频分析插件",
    "author": "MixVideo Team",
    "email": "team@mixvideo.com",
    "category": "analyzer",
    "tags": ["video", "opencv", "analysis", "computer-vision"],
    "dependencies": [],
    "permissions": ["file_read"],
    "config_schema": {
        "opencv": {
            "type": "object",
            "properties": {
                "scene_threshold": {
                    "type": "number",
                    "minimum": 0.0,
                    "maximum": 1.0,
                    "default": 0.3,
                    "description": "场景检测阈值"
                },
                "sample_rate": {
                    "type": "number",
                    "minimum": 0.0,
                    "maximum": 1.0,
                    "default": 1.0,
                    "description": "帧采样率"
                },
                "max_frames": {
                    "type": "integer",
                    "minimum": 1,
                    "default": 1000,
                    "description": "最大分析帧数"
                },
                "max_concurrent_jobs": {
                    "type": "integer",
                    "minimum": 1,
                    "default": 2,
                    "description": "最大并发任务数"
                }
            }
        }
    },
    "default_config": {
        "opencv": {
            "scene_threshold": 0.3,
            "sample_rate": 1.0,
            "max_frames": 1000,
            "max_concurrent_jobs": 2
        }
    }
}

# 插件类
PLUGIN_CLASS = OpenCVPlugin
